//
//  ViewController.swift
//  MyOfO
//
//  Created by Yuri on 2018/3/23.
//  Copyright © 2018年 Yuri. All rights reserved.
//

import UIKit
import SWRevealViewController
import FTIndicator

class ViewController: UIViewController, MAMapViewDelegate, AMapSearchDelegate, AMapNaviWalkManagerDelegate {
    
    //高德地图控件
    var mapView : MAMapView!
    
    @IBOutlet weak var pannelView: UIView!
    @IBOutlet weak var startBtn: UIButton!
    //底部的用户和通知独立出来是因为pannelView太大了 不好定位
    @IBOutlet weak var tabbarStackView: UIStackView!
    @IBOutlet weak var positionStackView: UIStackView!
    //动态调整空间的约束
    @IBOutlet weak var positionBottomConstraint: NSLayoutConstraint!
    
    var searchApi : AMapSearchAPI!
    var myPinAnnotation : MyPinAnnotation!
    
    var pinView : MAPinAnnotationView!
    var searchByUserMove = false
    
    var walkNaviManager : AMapNaviWalkManager!
    var start,end : CLLocationCoordinate2D!
    
    @IBOutlet weak var arrowBtn: UIButton!
    //pannelView是否展开，默认是展开的
    var isPannelCollasped = true
    
    @IBAction func arrowBtnClick(_ sender: UIButton) {
        movePannelView()
    }
    
    //底部Pannel view手势处理
    @IBAction func pannelViewGesture(_ sender: UIPanGestureRecognizer) {
        switch sender.state {
        case .changed:
            //当手势有变化的时候
            //将pannel view的手势 转换成 view
            let translte = sender.translation(in: view)
            if translte.y != 0 {
                movePannelView()
            }
        default:
            break
        }
    }
    
    //底部PannelView的收缩和展开
    func movePannelView() {
        let deltaY = self.view.frame.height / 3.6
        let deltaYForStartBtn = self.view.frame.height / 3
        if isPannelCollasped {
            arrowBtn.setImage(#imageLiteral(resourceName: "arrowup"), for: .normal)
            UIView.animate(withDuration: 0.3) {
                self.pannelView.transform = CGAffineTransform(translationX: 0, y: deltaY)
                self.startBtn.transform = CGAffineTransform(translationX: 0, y: deltaYForStartBtn)
                self.pannelView.alpha = 0.8
                self.tabbarStackView.transform = CGAffineTransform(translationX: 0, y: deltaY)
                //动态调整控件的约束
                self.positionBottomConstraint.constant -= deltaY
                self.view.layoutIfNeeded()
            }
        } else {
            arrowBtn.setImage(#imageLiteral(resourceName: "arrowdown"), for: .normal)
            UIView.animate(withDuration: 0.3) {
                self.pannelView.transform = .identity
                self.startBtn.transform = .identity
                self.pannelView.alpha = 1
                
                //动态调整控件的约束
                self.positionBottomConstraint.constant += deltaY
                self.view.layoutIfNeeded()
                
            }
            
            //通知和用户两个按钮延迟出现动画，两种方法
//            UIView.animate(withDuration: 0.3, delay: 0.15, options: .allowAnimatedContent, animations: {
//                self.tabbarStackView.transform = .identity
//            }, completion: nil)
            UIView.animate(withDuration: 0.45) {
                self.tabbarStackView.transform = .identity
            }
        }
        isPannelCollasped = !isPannelCollasped
    }
    
    @IBAction func locationBtnTap(_ sender: UIButton) {
        //点击定位
        searchBikeNearBy()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置导航条的左右按钮和中间Logo图标
        navigationItem.titleView = UIImageView(image: #imageLiteral(resourceName: "ofoLogo"))
        navigationItem.leftBarButtonItem?.image = #imageLiteral(resourceName: "leftTopImage").withRenderingMode(.alwaysOriginal)
        navigationItem.rightBarButtonItem?.image = #imageLiteral(resourceName: "rightTopImage").withRenderingMode(.alwaysOriginal)
        
        //设定导航条返回按钮没有文字
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        
        //侧滑菜单
        if let revealVC = revealViewController() {
            //设置侧滑菜单的宽度
            revealVC.rearViewRevealWidth = 280.0
            navigationItem.leftBarButtonItem?.target = revealVC
            navigationItem.leftBarButtonItem?.action = #selector(SWRevealViewController.revealToggle(_:))
            view.addGestureRecognizer(revealVC.panGestureRecognizer())
        }
        
        pannelView.layer.cornerRadius = view.frame.width
        pannelView.layer.shadowRadius = 10
        pannelView.layer.shadowOffset = CGSize(width: -1, height: -1)
        pannelView.layer.shadowOpacity = 0.2
        pannelView.layer.shadowColor = UIColor.darkText.cgColor
        
        mapView = MAMapView(frame: view.bounds)
        view.addSubview(mapView)
        view.bringSubview(toFront: pannelView)
        view.bringSubview(toFront: tabbarStackView)
        view.bringSubview(toFront: positionStackView)
        
        mapView.delegate = self
        
        mapView.zoomLevel = 17
        //定位
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        
        //初始化搜索API
        searchApi = AMapSearchAPI()
        searchApi.delegate = self
        
        //步行导航Manager
        walkNaviManager = AMapNaviWalkManager()
        walkNaviManager.delegate = self
       
        
    }
    
    //搜索附近的小黄车
    func searchBikeNearBy() {
        print("searchBikeNearBy")
        searchByUserMove = false
        searchCustomLocation(center: mapView.userLocation.coordinate)
    }
    
    //搜索自定义位置周边数据
    //由于没有小黄车的数据
    //我们使用餐馆代替小黄车（搜索到餐馆就认为是小黄车）
    func searchCustomLocation(center: CLLocationCoordinate2D) {
        let request = AMapPOIAroundSearchRequest()
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(center.latitude), longitude: CGFloat(center.longitude))
        request.keywords = "餐馆"
        request.requireExtension = true
        request.radius = 500
        searchApi.aMapPOIAroundSearch(request)
    }
    
    // MARK: - MAP Search Delegate
    //POI搜索完成
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        if response.count == 0 {
            print("没有小黄车")
            return
        }
        
        //添加标注到地图上
        var annotations : [MAPointAnnotation] = []
        annotations = response.pois.map({
            let annotation = MAPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees($0.location.latitude), longitude: CLLocationDegrees($0.location.longitude))
            if $0.distance < 200 {
                annotation.title = "红色区域内开锁任意小黄车"
                annotation.subtitle = "骑行10分钟可得现金红包"
            } else {
                annotation.title = "正常可用"
            }
            return annotation
        })
        
        mapView.addAnnotations(annotations)
        
        if !searchByUserMove {
            //显示所有标注
            mapView.showAnnotations(annotations, animated: true)
        }
        
    }
    
    //MARK: - MapView deletgate
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        //用户自己的位置，不需要自定义
        if annotation is MAUserLocation {
            return nil
        }
        
        if annotation is MyPinAnnotation {
            let reuseid = "anchor"
            var annotionView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseid) as? MAPinAnnotationView
            
            if annotionView == nil {
                annotionView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseid)
            }
            annotionView?.image = #imageLiteral(resourceName: "homePage_wholeAnchor")
            
            annotionView?.canShowCallout = false
            annotionView?.animatesDrop = false
            annotionView?.isDraggable = true
            
            pinView = annotionView
            
            return annotionView
        }
        
        let reuseid = "myuseid"
        var annotionView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseid) as? MAPinAnnotationView
        
        if annotionView == nil {
            annotionView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseid)
        }
        
        if annotation.title == "正常可用" {
            annotionView?.image = #imageLiteral(resourceName: "HomePage_nearbyBike")
        } else {
            annotionView?.image = #imageLiteral(resourceName: "HomePage_nearbyBikeRedPacket")
        }
        
        annotionView?.canShowCallout = true
        annotionView?.animatesDrop = true
        annotionView?.isDraggable = false
        
        return annotionView
    }
    
    //地图初始化完成
    func mapInitComplete(_ mapView: MAMapView!) {
        searchBikeNearBy()
        
        myPinAnnotation = MyPinAnnotation()
        myPinAnnotation.coordinate = mapView.centerCoordinate
        myPinAnnotation.lockedScreenPoint = CGPoint(x: view.bounds.width / 2, y: view.bounds.height / 2)
        myPinAnnotation.isLockedToScreen = true
        
        mapView.addAnnotation(myPinAnnotation)
        mapView.showAnnotations([myPinAnnotation], animated: true)
        
    }
    
    //地图移动完成之后回调
    func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
        //用户移动地图后，重新搜索小黄车的数据
        if wasUserAction {
            searchByUserMove = true
            myPinAnnotation.isLockedToScreen = true
            pinAnimation()
            searchCustomLocation(center: mapView.centerCoordinate)
        }
    }
    
    //添加了标记到地图上
    func mapView(_ mapView: MAMapView!, didAddAnnotationViews views: [Any]!) {
        let aViews = views as! [MAAnnotationView]
        for aView in aViews {
            guard aView.annotation is MAPointAnnotation else {
                continue
            }
            
            //缩放动画
            //从0开始放大
            aView.transform = CGAffineTransform(scaleX: 0, y: 0)
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: [], animations: {
                aView.transform = .identity
            }, completion: nil)
        }
    }
    
    //点击了地图上的大头针
    func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
        print("点击了大头针,开始步行导航")
        start = myPinAnnotation.coordinate
        end = view.annotation.coordinate
        
        let startPoint = AMapNaviPoint.location(withLatitude: CGFloat(start.latitude), longitude: CGFloat(start.longitude))!
        let endPoint = AMapNaviPoint.location(withLatitude: CGFloat(end.latitude), longitude: CGFloat(end.longitude))!
        
        walkNaviManager.calculateWalkRoute(withStart: [startPoint], end: [endPoint])
    }
    
    //画线渲染-设置样式
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if overlay is MAPolyline {
            myPinAnnotation.isLockedToScreen = true
            mapView.visibleMapRect = overlay.boundingMapRect
            
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: overlay)
            renderer.lineWidth = 8.0
            renderer.strokeColor = UIColor.cyan
            return renderer
        }
        return nil
    }
    
    // MARK: - 大头针动画
    func pinAnimation() {
        //坠落效果，Y轴加位移
        let endFrame = pinView.frame
        
        pinView.frame = endFrame.offsetBy(dx: 0, dy: -15)
        
        UIView.animate(withDuration: 1, delay: 9, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: {
            self.pinView.frame = endFrame
        }, completion: nil)
    }
    
    // MARK: - AMapNaviWalkManagerDelegate
    //步行导航结束
    func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) {
        print("步行导航成功")
        mapView.removeOverlays(mapView.overlays)
        //在地图上添加线路
        var coordinates = walkManager.naviRoute!.routeCoordinates!.map({
            return CLLocationCoordinate2D(latitude: CLLocationDegrees($0.latitude), longitude: CLLocationDegrees($0.longitude))
        })
        
        let polyline: MAPolyline = MAPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
        
        mapView.add(polyline)
        
        //提示距离和用时
        let walkMinute = (walkManager.naviRoute?.routeTime)! / 60
        var timeString = "1分钟以内"
        if walkMinute > 0 {
            timeString = walkMinute.description + "分钟"
        }
        
        let hinTitle = "步行" + timeString
        let hintSubtitle = "距离" + (walkManager.naviRoute?.routeLength.description)! + "米"
        
//        let alertControl = UIAlertController(title: hinTitle, message: hintSubtitle, preferredStyle: .alert)
//        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
//        alertControl.addAction(action)
//        self.present(alertControl, animated: true, completion: nil)
        
        FTIndicator.setIndicatorStyle(.dark)
        FTIndicator.showNotification(with: #imageLiteral(resourceName: "clock"), title: hinTitle, message: hintSubtitle)
        
    }
    
    func walkManager(_ walkManager: AMapNaviWalkManager, onCalculateRouteFailure error: Error) {
        print("步行导航失败：\(error.localizedDescription)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

